' Animals Amendment Validation Script
Option Strict Off
imports System
imports Humans=PHSRAG.Insight21.Humans
imports PHSRAG.Insight21.BusinessObjects
imports FormsManagement = PHSRAG.Insight21.FormsManagement
imports System.Collections
imports Utility=PHSRAG.Utility

module Script
    sub Main()

        ' Pages for rediction
        const staffPageRedirection = 0
        const overviewPageRedirection = -2
		const AttachmentsPageRedirection = -1

		dim attachmentsLogItemAdded as boolean = false

        if intrinsicProtocol.PIPersonId = 0 then ' if no PI, log that error, else, log org error
            Dim logItem As New Humans.LogItem(intrinsicCachePolicy)
            logItem.QuestionnaireVersionId = staffPageRedirection
            logItem.QuestionnaireAnswerId = staffPageRedirection
            logItem.Type = "Staff"
            logItem.Category = "No PI"
            logItem.QuestionName ="Staff"
            logItem.Answer = "Staff"
            logItem.Description = "Protocol must have a staffed Principal Investigator"
            logItem.Completed = False
            SaveLogItem(logItem)
        end if

        'Check if Flowchart is attached. This document is required for all the protocols
        Dim attachedDocuments As ArrayList = intrinsicProtocolProcess.ProtocolDocuments
        Dim isFlowchartAttached as boolean 
        For Each pD As Humans.ProtocolDocument In attachedDocuments
            If ((FormsManagement.Constants.AttachmentType.Flowchart = pD.Type) and (pD.IsHardCopy or pD.DocumentId >0)) Then
                isFlowchartAttached = True
            End if  
        Next

        	

        ' count the number of times they answered the Primary question on the sponorFunding questionnaire.
        Dim primarySponsorCount as integer = 0
        Dim sponsorChange as boolean = false
        Dim sponsorType as string
		dim verifyStaff as boolean = false
		Dim qV As FormsManagement.QuestionnaireVersion
       	Dim documentsToBeAttached As new ArrayList() 
        Dim additionalNumber as integer = 0
        Dim speciesCount as integer = 0

        For Each questionnaireAnswer As FormsManagement.QuestionnaireAnswer In intrinsicProtocolVersion.QuestionnaireAnswers

			'Validate staff only if the AME involves any performance site changes or staff changes
			if questionnaireAnswer.QuestionnaireVersion.Questionnaire.Name = "IACUCAmendment" then
				dim answers as System.Collections.ArrayList = questionnaireAnswer.GetAnswers("ComStaff")
				if ( answers.Count > 0 ) then
					Dim primaryAnswer as FormsManagement.Answer = answers(0)
					if primaryAnswer.Value = "STAFF" then
						verifyStaff = true
					end if
				end if
				answers = questionnaireAnswer.GetAnswers("InsightProd")
				if (answers.Count > 0) then
					if (answers(0).Value = "N") then
						verifyStaff = true
					end if
				end if
				answers = questionnaireAnswer.GetAnswers("TopChoice")
				if (not answers is nothing) then
				    if ( answers.Count > 0 ) then
					    Dim topChoice as FormsManagement.Answer = answers(0)
					    if topChoice.Value = "N" then
						   if (not isFlowchartAttached) then
                            LogMissingItem(-1, -1, "Attachments", string.empty, string.empty, string.empty, "Flowchart must be attached.")
                            attachmentsLogItemAdded = true
                            end if	
					    end if
				    end if
				end if 
				
				Dim additionalAnimals as string = questionnaireAnswer.GetAnswerValue("AddNum")
				if IsNumeric(additionalAnimals) then
				    additionalNumber = FormatNumber(additionalAnimals)
				end if
				
				Dim hazardAnswer as String = questionnaireAnswer.GetAnswerValue("ComHazards")
				if hazardAnswer = "HAZARDS" then
                    intrinsicProtocol.BiologicalAgent = false
                    intrinsicProtocol.ToxicChem = false
                    intrinsicProtocol.RadioIsotope = false
				end if
			end if			

            ' Create a validation error if there is a QA with a default name (for multiples) 
            ' --> We do this so that "Move to Rex" doesn't fail when trying to move over blank forms
            ' --> Note that we don't handle Sponsors b/c we only move over the primary sponsor to REX so blank
            ' forms are okay and won't fail the "Move to Rex"
            if (questionnaireAnswer.Name = FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Hazardous)
                Dim category as string = "Hazardous Agent Administration and Use"
                Dim description as string = "You have indicated that the study will include a hazardous material.  Please either complete the form or remove it from the study."
                Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, overviewPageRedirection, overviewPageRedirection, category, category, "", "", description, false)
                SaveLogItem(logItem)	
            else if (questionnaireAnswer.Name = FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Procedures)
                Dim category as string = "Procedures"
                Dim description as string = "You have indicated that the study will include a surgical procedure.  Please either complete the form or remove it from the study."
                Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, overviewPageRedirection, overviewPageRedirection, category, category, "", "", description, false)
                SaveLogItem(logItem)	
            else if (questionnaireAnswer.Name = FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Tumor)
                Dim category as string = "Tumor Production"
                Dim description as string = "You have indicated that the study will include tumor production.  Please either complete the form or remove it from the study."
                Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, overviewPageRedirection, overviewPageRedirection, category, category, "", "", description, false)
                SaveLogItem(logItem)	
            end if

            if questionnaireAnswer.QuestionnaireVersion.Questionnaire.Name = "Sponsor Funding" then
                sponsorChange = true
                if questionnaireAnswer.Action <> FormsManagement.QuestionnaireAnswer.UserAction.Remove then
                    'If the sponsor type is None, then no primary sponsor is required
                    Dim sponsorTypes as System.Collections.ArrayList = questionnaireAnswer.GetAnswers("SponsorType")
                    if ( sponsorTypes.Count > 0 ) then
                        sponsorType = sponsorTypes(0).Value
                    end if

                    Dim answers as System.Collections.ArrayList = questionnaireAnswer.GetAnswers("PrimarySponsor")

                    if ( answers.Count > 0 ) then
                        Dim primaryAnswer as FormsManagement.Answer = answers(0)
                        if primaryAnswer.Value = "Y" then
                            primarySponsorCount = primarySponsorCount + 1
                        end if
                    end if
                end if
            end if ' end if questionnaireAnswer.QuestionnaireVersion.Questionnaire.Name = "Sponsor Funding" then

            if questionnaireAnswer.QuestionnaireVersion.Questionnaire.Name = "Potential Pain and Distress" then
                Dim categoryNumber as String = questionnaireAnswer.GetAnswerValue("CatBNum")
                
                if IsNumeric ( categoryNumber ) then
                    speciesCount = FormatNumber(categoryNumber)
                end if

                categoryNumber = questionnaireAnswer.GetAnswerValue("CatCNum")
                if IsNumeric ( categoryNumber ) then
                    speciesCount = speciesCount + FormatNumber(categoryNumber)
                end if

                categoryNumber = questionnaireAnswer.GetAnswerValue("CatDNum")
                if IsNumeric ( categoryNumber ) then
                    speciesCount = speciesCount + FormatNumber(categoryNumber)
                end if

                categoryNumber = questionnaireAnswer.GetAnswerValue("CatENum")
                if IsNumeric ( categoryNumber ) then
                    speciesCount = speciesCount + FormatNumber(categoryNumber)
                end if
            end if

            if questionnaireAnswer.QuestionnaireVersion.Questionnaire.Name = "Hazardous Agent Administration and Use"
                Dim hazardType as string = questionnaireAnswer.GetAnswerValue("HazardType")
                select case hazardType
                    case "Bio"
                        intrinsicProtocol.BiologicalAgent = true
                    case "Chem"
                        intrinsicProtocol.ToxicChem = true
                    case "Rad"
                        intrinsicProtocol.RadioIsotope = true
                end select
            end if
        next
        
        ' Ensure the number we're adding in the amendment form is equal to the number added in the 
        ' Potential Pain and Distress form - Note Protocol.NumberOfAnimals isn't updated yet.
        if speciesCount - intrinsicProtocol.NumberOfAnimals <> additionalNumber and additionalNumber > 0 then
            Dim category as string = "Potential Pain and Distress"
            Dim description as string = "The additional animals in the pain category breakdown questions do not equal the total number of animals to be added from the IACUCAmendment."
            Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, overviewPageRedirection, overviewPageRedirection, category, category, "", "", description, false)
            SaveLogItem(logItem)	
        end if

        dim verifiedQuestionnaires as string = "|"
		For Each questionnaireAnswer As FormsManagement.QuestionnaireAnswer In intrinsicProtocolVersion.QuestionnaireAnswers
			qv = questionnaireAnswer.QuestionnaireVersion
			'Check if this type of document was already verified with the attachments
			dim verifyQuestionnaire = "|" + qv.Questionnaire.Name + "|"
			if verifiedQuestionnaires.IndexOf(verifyQuestionnaire) < 0  then
				verifiedQuestionnaires = verifiedQuestionnaires + verifyQuestionnaire

				' Get the documents needed to be attached from the questionnaire version.
				documentsToBeAttached = qV.documents
	            
				'The following for loop checks the availability of the required documents
           		For Each qD As FormsManagement.QuestionDocument In documentsToBeAttached
           			If (qD.Type <> Nothing) Then
               			If (qD.IsRequired) Then
       						dim supposedPDCountForQDType as integer = 0
       						dim actualPDCountForQDType as integer = 0

							'Get the type of the question. If the question's type is MultiInput or DropDownMultiSelect, then for each entry, need a enforce a document
							dim isMultiInputOrMultiSelect as boolean = false
							for each item as FormsManagement.QuestionnaireItem in qV.Items
								if (item.Name = qD.ItemName) then
									if (item.Type = FormsManagement.QuestionnaireItem.MultiSelectItemType or item.Type = FormsManagement.QuestionnaireItem.DropDownMultiSelectItemType) then
										isMultiInputOrMultiSelect = true
									end if
									exit for
								end if
							next
					
							'if (questionnaireAnswer.VersionAllowsMultiple) then
								dim similarQAs as ArrayList
								similarQAs = intrinsicProtocolVersion.GetAllQVQAs(questionnaireAnswer.QuestionnaireVersion.Id)
								
								if (not isMultiInputOrMultiSelect) then
									for each qA as FormsManagement.QuestionnaireAnswer in similarQAs
										For each answer as FormsManagement.Answer in qA.GetAnswers(qD.ItemName)
											if (answer.value = qD.ItemValue) then
												
												supposedPDCountForQDType = supposedPDCountForQDType + 1
												exit for
											end if
										Next
									next
								else 
									for each qA as FormsManagement.QuestionnaireAnswer in similarQAs
										supposedPDCountForQDType = supposedPDCountForQDType + questionnaireAnswer.GetAnswers(qD.ItemName).Count
									next
									
								end if
								
								'Get the attached documents from the protocol document.
								For Each pD As Humans.ProtocolDocument In intrinsicProtocolProcess.ProtocolDocuments
									'If the user has opted to send the hard copy of the document,No Log Item should be logged.
									If ((qD.Type = pD.Type) and (pD.IsHardCopy or pD.DocumentId >0)) Then
										actualPDCountForQDType = actualPDCountForQDType + 1
									End if  
								Next 
								
								If supposedPDCountForQDType > actualPDCountForQDType Then
									Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, -1, -1, "Attachments", "Attachments", qD.ItemName, qD.ItemValue, qD.ValidationMessage, false)
									SaveLogItem(logItem)
									attachmentsLogItemAdded = true
								End If
							'end if 'version allows multiple
						End If
					end if
           		Next ' 'end for loop that checks the availability of the required documents
           	End If
		next 'QUESTIONNAIRE ANSWER	

		'verify if all the ProtocolDocument records are either marked as hardcopy or there is an attachment tied to it
		If not attachmentsLogItemAdded then
			For Each pD As Humans.ProtocolDocument In intrinsicProtocolProcess.ProtocolDocuments
				If not (pD.IsHardCopy or pD.DocumentId >0) Then
					LogMissingItem(AttachmentsPageRedirection, AttachmentsPageRedirection, _
							"Attachments", string.empty, string.empty, string.empty, "Attachment missing for " + pD.Name)
				End if  
			Next
		End If

        ' Check that they've answered the Primary Sponsor question only once. 
        if (sponsorChange and primarySponsorCount <> 1) then
            if primarySponsorCount = 0 and sponsorType <> "None" then
                LogMissingItem(-2, -2, "Sponsor Funding", string.empty, string.empty, string.empty, "The protocol must have a Primary Sponsor. You must indicate this by answering yes to the Primary sponsor question.")			
            else if primarySponsorCount > 1 then
                LogMissingItem(-2, -2, "Sponsor Funding", string.empty, string.empty, string.empty, "You have answered yes to the Primary Sponsor question for more than one sponsor. Only one can be marked as the Primary sponsor.")			
            end if			
        end if

       'Validate staff only if the AME involves any performance site changes or staff changes
		if (verifyStaff) then

			Dim studyStaffCollection As Humans.StudyStaff = new Humans.StudyStaff(intrinsicCachePolicy)
			studyStaffCollection.Load(intrinsicConnection,intrinsicProtocolProcess.protocolId,intrinsicProtocolProcess.Id)
			Dim studyStaff as ArrayList = studyStaffCollection.GetStudyStaffList()

			Dim noOfPIs as integer = 0
			' Check that each staffPerson has a role
			For Each person as Humans.StaffPerson in studyStaff
				if person.Role.trim() = "Principal Investigator" then
					noOfPIs = noOfPIs + 1
				else if person.Role.trim()="" then
					Dim logItem As New Humans.LogItem(intrinsicCachePolicy)
					logItem.QuestionnaireVersionId=0'qV.Id(value is being set to zero(0),just to redirect the user to the staff and access page)
					logItem.QuestionnaireAnswerId=0'questionnaireAnswer.Id(value is being set to zero(0),just to redirect the user to the staff and access page)
					logItem.Type ="Study Site"
					logItem.Category ="Study Site"
					logItem.QuestionName = "Staff role"
					logItem.Answer =""
					logItem.Description ="Each staff person must be assigned with a role." 'qI.ValidationMessage(There exists no validationMessage for this qI,so the Description is hardCoded)
					logItem.Completed =False
					SaveLogItem(logItem)				
					exit for
				End If				
			Next	

			if noOfPIs > 1 Then
				Dim logItem As New Humans.LogItem(intrinsicCachePolicy)
				logItem.QuestionnaireVersionId=0'qV.Id(value is being set to zero(0),just to redirect the user to the staff and access page)
				logItem.QuestionnaireAnswerId=0'questionnaireAnswer.Id(value is being set to zero(0),just to redirect the user to the staff and access page)
				logItem.Type ="Staff"
				logItem.Category ="Multiple PIs"
				logItem.QuestionName = "Staff"
				logItem.Answer ="Staff"
				logItem.Description ="Only one Principal Investigator is allowed on a protocol." 'qI.ValidationMessage(There exists no validationMessage for this qI,so the Description is hardCoded)
				logItem.Completed =False
				SaveLogItem(logItem)
			End if
        
		end if 'Validate staff only if the AME involves any performance site changes or staff changes

        intrinsicProtocol.Save(intrinsicConnection)

    End Sub

    'Save LogItem
    Sub SaveLogItem(ByVal logItem As Humans.LogItem)
        intrinsicProtocolProcess.SaveLogItem(logItem)
    End Sub

    private function LogMissingItem(byval questionnaireVersionId as integer, byval questionnaireAnswerId as integer, byval logType as string, byval category as string, byval questionName as string, byval answer as string, byval description as string)
        Dim logItem As New Humans.LogItem(intrinsicCachePolicy)
        logItem.QuestionnaireVersionId = questionnaireVersionId
        logItem.QuestionnaireAnswerId = questionnaireAnswerId
        logItem.Type = logType
        logItem.QuestionName = questionName
        logItem.Category = category
        logItem.Answer = answer
        logItem.Description = description
        logItem.Completed =False
        SaveLogItem(logItem)
    end function
					
end module